package main

import (
	"database/sql"
	"errors"
	"fmt"
	"time"

	"github.com/google/uuid"
	"gorm.io/driver/mysql"
)
import "gorm.io/gorm"

type User struct {
	ID           uint
	Name         string         //默认是空字符串
	Email        *string        //默认是null
	Age          uint8          //默认是0
	Birthday     *time.Time     //默认是null
	MemberNumber sql.NullString //默认是null
	ActivatedAt  sql.NullTime   //默认是null
	CreatedAt    time.Time      //默认是当前时间
	UpdatedAt    time.Time      //默认是当前时间
	ignored      string
	Uuid         uuid.UUID
}

type Author struct {
	gorm.Model
	Name  string
	Email string
}

type Blog struct {
	Author Author `gorm:"embedded"`
	Upvote uint32
}

func (user *User) BeforeCreate(tx *gorm.DB) (err error) {
	user.Uuid = uuid.New()

	if user.Age >= 200 {
		return errors.New("cannot create a new user")
	}
	return
}

func main() {
	fmt.Println("hello world primer")

	db := InitDB()

	//创建或同步表结构
	//db.AutoMigrate(&User{})
	//db.AutoMigrate(new(Author), new(Blog))

	//插入
	//email := "12321321@dd.com"
	//user := &User{Name: "jack2", Email: &email, Age: 200}
	//result := db.Create(user)
	//fmt.Println("RowsAffected", result.RowsAffected)
	//fmt.Println("Error", result.Error)
	//fmt.Println("ID", user.ID)

	//查询
	//user := User{}
	//db.First(&user)
	//db.Debug().First(&user)
	//db.Last(&user)
	//db.Debug().Last(&user)
	//db.Debug().First(&user, 2)

	//更新
	//user := User{}
	//db.Debug().First(&user, 2)
	//user.Name = "messi"
	//db.Debug().Save(&user)
	////更新单列
	//db.Debug().Model(&user).Update("age", 20)
	//
	////更新多列
	//now := time.Now()
	//newEmail := "111@aaa.com"
	//db.Debug().Model(&user).Updates(User{Birthday: &now, Email: &newEmail})

	//删除
	user := User{}
	db.Debug().Delete(&user, 3)

	//软删除
	db.AutoMigrate(new(Author), new(Blog))
	blog := &Blog{
		Author: Author{
			Name:  "messi",
			Email: "222@bbb.com",
		},
		Upvote: 0,
	}
	db.Debug().Save(blog)
	db.Debug().Delete(&blog)

}

func InitDB() *gorm.DB {
	db := ConnectDB()
	return db
}

func ConnectDB() *gorm.DB {
	//dsn := "user:pass@tcp(127.0.0.1:3306)/gorm?charset=utf8mb4&parseTime=True&loc=Local"
	//db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

	db, err := gorm.Open(mysql.New(mysql.Config{
		DSN:                       "root:123456@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local",
		DefaultStringSize:         256,   // string 类型字段的默认长度
		DisableDatetimePrecision:  true,  // 禁用 datetime 精度，MySQL 5.6 之前的数据库不支持
		DontSupportRenameIndex:    true,  // 重命名索引时采用删除并新建的方式，MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
		DontSupportRenameColumn:   true,  // 用 `change` 重命名列，MySQL 8 之前的数据库和 MariaDB 不支持重命名列
		SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置
	}), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	return db
}
